from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from booking.models import recording
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import JsonResponse 
from datetime import date, timedelta 
from jwt import exceptions
import jwt
import time

JWT_KEY='whut'
TIME_OUT=9000

#生成token
def generate_token(uid,salt=JWT_KEY):
    # 设置headers，即加密算法的配置
    headers = {
    "alg": "HS256",
    "typ": "JWT"
    }
    # 设置超时时间：当前时间的600s以后超时
    exp = int(time.time() + TIME_OUT)
    # 配置payload，一般是登录成功的用户之类的，因为jwt的主体信息很容易被解码，所以不要放敏感信息
    payload = {
    "name": uid,
    "exp": exp
    }
    token = jwt.encode(payload=payload, key=salt, algorithm='HS256', headers=headers)
    return token

#验证token
def verify_token(token,salt=JWT_KEY):
    payload = None
    msg = None
    try:
        payload = jwt.decode(token, salt, verify=True, algorithms='HS256')
    except exceptions.ExpiredSignatureError:
        msg = 'token已失效'
    except jwt.DecodeError:
        msg = 'token认证失败'
    except jwt.InvalidTokenError:
        msg = '非法的token'
    return (payload, msg)

#登录
@csrf_exempt
def logIn(request):
    if request.method=="POST":
        data = json.loads(request.body) 
        user = authenticate(request, username=data["username"], password=data["password"])
        response = {} 
        
        if user is not None:
            login(request, user)
            token = generate_token(user.id)
            print(token)
            response["token"] = token
            response["code"] = 200
            response["msg"] = "登录成功" 
            response["uid"] =user.id
        else:
            response["code"] = 400
            response["msg"] = "用户名或密码错误"
        return JsonResponse(response)
    
#验证是否登录，重定向未登录的功能页面到登录页面
@csrf_exempt
def verify(request):
    if request.method=="POST":
        data = json.loads(request.body) 
        token = data['token']
        print(token)
        payload, msg = verify_token(token)
        print(payload['name'])
        response={}
        print(msg)
        if(str(msg) == "None"):
            response["status"] = "Y"
            response["uid"] =payload['name']
        else:
            response["status"] = "N"    
        return JsonResponse(response)  

#注册
@csrf_exempt
def logOn(request):
    if request.method=="POST":
        data = json.loads(request.body)
        response = {}
        print('111')
        try:  
            newUser=User.objects.create_user(username=data["username"], password=data["password"])
            newUser.save()
            response["code"] = 200
            response["msg"] = "注册成功"
        except:
            response["code"] = 400
            response["msg"] = "注册失败"
        return JsonResponse(response)  

#提交预约信息
@csrf_exempt
def submit(request):
    if request.method=="POST":
        data = json.loads(request.body)
        user = request.user
        today = date.today()
        instance = recording()
        instance.username = user.username
        print(user.username)
        instance.uid = user.id
        print(user.id)
        instance.name = data["name"]
        print(data["name"])
        instance.date = today+timedelta(days=int(data["date"]))
        print(data["date"])
        instance.period = data["period"]
        print(data["period"])
        instance.status = "待参观"
        print("待参观")
        instance.phone = data["phone"]
        print(data["phone"])
        instance.idcard = data["idcard"]
        print(data["idcard"])
        response = {} 
        try:
            instance.save()
            response["code"] = 200
            response["msg"] = "预约成功"
        except:
            response["code"] = 400
            response["msg"] = "预约失败"
        return JsonResponse(response)  

#退票
@csrf_exempt
def remove(request):
    if request.method=="POST":
        data = json.loads(request.body)
        recording.objects.filter(id=data["tid"]).update(status = "已退票")
        response = {}
        response["code"] = 200
        response["msg"] = "退票成功"
        return JsonResponse(response)  

#获取预约记录
@csrf_exempt
def getitems(request):
    if request.method=="GET":
        user = request.user
        print(user.id)
        results = recording.objects.filter(uid = user.id)
        data=[]
        for i in range(len(results)):
            dic = {}
            dic["date"] = str(results[i].date)
            vis = str(results[i].created_at+timedelta(hours=8))
            dic["vis"] = vis[:19]
            dic["period"] = str(results[i].period)
            dic["name"] = str(results[i].name)
            dic["phone"] = str(results[i].phone)
            dic["idcard"] = str(results[i].idcard)
            dic["status"] = str(results[i].status)
            dic["tid"] = str(results[i].id)
            data.append(dic)
        response={}
        response["code"] = 200
        response["msg"] = "获取成功"
        response["data"] = data
        return JsonResponse(response) 

#获取未来7天的票量
@csrf_exempt
def askdateinf(request):
    if request.method=="POST":
        today = date.today() 
        data={} 
        for i in range(1,8):
            day=today+timedelta(days=i)
            results = recording.objects.filter(date=day)
            ss="d"+str(i) 
            data[ss] = len(results)
        return JsonResponse(data)  


